######################################################
# Code to create Figure 1: Over Time Trends in Extremity Perceptions
######################################################

############################
#Packages
############################
library(survey)
library(srvyr)
library(directlabels)
library(rio)
library(tidyverse)

############################
#Import Data and Clean
############################

#######Data
combdata <- import("./Data/pew_cnn_comb.Rda")

#######Declare Survey Design
comb_design <- combdata %>%
  filter(!is.na(weight)) %>%  #This removes some observations with missing weight data
  srvyr::as_survey_design(ids = 1, weights=weight)

########Get weighted means
overall_means <- comb_design %>%
  mutate(too_extreme1 = factor(too_extreme1, 
                               levels=c(1,2,3), 
                               labels=c("Neither", "One Party", "Both Parties"))) %>%
  filter(!is.na(too_extreme1)) %>%
  group_by(sdate, too_extreme1) %>%
  summarize(proportion = srvyr::survey_mean(na.rm=T)) %>%
  mutate(lower = proportion - (1.96*proportion_se), 
         upper = proportion + (1.96*proportion_se), 
         sdate = as.Date(sdate))

#######Figure
f1 <- overall_means %>%
  mutate(label =if_else(sdate == max(sdate), as.character(too_extreme1), NA_character_)) %>%
  ggplot(aes(x=sdate, y=proportion, shape=too_extreme1, linetype=too_extreme1)) + 
  geom_point() + 
  geom_smooth(method=lm, se=F, color="black") + 
  scale_y_continuous(limits=c(0,1)) + 
  theme_light(16) + 
  labs(y = "Proportion Giving Response", 
       x = "Time",
       shape = "Response", 
       linetype = "Response") + 
  scale_x_date(date_breaks= "2 year", date_labels="%Y") + 
  theme(legend.position="top",
        legend.direction="horizontal", 
        legend.background = element_rect()) + 
  scale_shape_manual(values=c(17, 1, 0)) + 
  scale_linetype_manual(values=c(1, 3, 2)) + 
  theme(legend.position=c(0.30,0.95),
      legend.direction="horizontal", 
      legend.background = element_rect(), 
      legend.box.background = element_rect(colour = "black")) 

f1a <- lemon::reposition_legend(f1, 'top left', offset= 0.002 )  

ggsave(plot = f1a, "./Tables_Figures/figure1.png", 
       height=6, width=10, dpi=1200)
